package com.imaker.frame.network

import android.util.Log
import com.imaker.frame.utils.Constants
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit
import javax.net.ssl.X509TrustManager

/**
 * @Description:请求网络
 * @author ziheng
 * @date 2022/12/5 18:07
 */
object RetrofitApi {

    var service: ApiService

    init {
        val logInterceptor = HttpLoggingInterceptor {
            Log.d("OkHttp Log : ", it)
        }.setLevel(HttpLoggingInterceptor.Level.BODY)

        val okHttpClient = OkHttpClient().newBuilder()
            .callTimeout(10, TimeUnit.SECONDS)
            .connectTimeout(10, TimeUnit.SECONDS)
            .readTimeout(10, TimeUnit.SECONDS)
            .writeTimeout(10, TimeUnit.SECONDS)
            .retryOnConnectionFailure(true)
            .followRedirects(false)
            .addInterceptor(logInterceptor)
            .addInterceptor(HeaderInterceptor())
            .sslSocketFactory(
                SSLSocketClient.sslSocketFactory,
                SSLSocketClient.trustManager[0] as X509TrustManager
            )
            .hostnameVerifier(SSLSocketClient.hostnameVerifier)
            .build()

        val retrofit = Retrofit.Builder()
            .client(okHttpClient)
            .baseUrl(Constants.BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build()
        service = retrofit.create(ApiService::class.java)
    }
}